const jwt = require("jsonwebtoken");
const config = require("../utils/config");
const utils = require("../utils/utils");

// 状态码
const codeObj = config.codeObj;

// 登录
exports.login = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  const secretKey = config.jwt.secret;
  const params = req.body;
  let paramsValid = utils.paramsValid(params, ["username", "password"]);
  if (paramsValid) {
    resObj.code = codeObj.fail;
    resObj.message = paramsValid + "不能为空";
    res.end(JSON.stringify(resObj));
    return;
  }
  // 执行查询
  let sql = `select * from user where user_name=? and password=?`;
  req.db.driver.execQuery(
    sql,
    [params.username, params.password],
    (err, data) => {
      if (err) {
        resObj.code = codeObj.fail;
        resObj.message = err.sqlMessage;
      } else {
        if (data.length > 0) {
          const payload = {
            dataId: data[0].data_id,
            userName: data[0].user_name,
          };
          resObj.userInfo = payload;
          resObj.accessToken = jwt.sign(payload, secretKey, {
            expiresIn: config.jwt.expiresIn.accessToken,
          });
          resObj.refreshToken = jwt.sign(payload, secretKey, {
            expiresIn: config.jwt.expiresIn.refreshToken,
          });
        } else {
          resObj.code = codeObj.fail;
          resObj.message = "账号密码错误";
        }
        return res.json(resObj);
      }
      res.json(resObj);
    }
  );
};

// 获取用户详情
exports.getUserInfo = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  const info = req.auth;
  resObj.data = {
    userId: info.dataId,
    userName: info.userName,
  };
  res.json(resObj);
};

// 刷新token
exports.refreshToken = (req, res) => {
  let resObj = {
    code: codeObj.success,
  };
  const secretKey = config.jwt.secret;
  const token = req.query.token; // 此 token 为 refresh_token
  let dataId = "",
    userName = "";
  try {
    const userInfo = jwt.verify(token, secretKey);
    dataId = userInfo.dataId;
    userName = userInfo.userName;
  } catch (error) {
    resObj.code = codeObj.fail;
    resObj.message = "token 失效，请重新登录";
    return res.status(401).json(resObj);
  }
  let sql = `select * from user where user_name=?`;
  req.db.driver.execQuery(sql, [userName], (err, data) => {
    if (err) {
      resObj.code = codeObj.fail;
      resObj.message = err.sqlMessage;
    } else {
      if (data.length > 0) {
        const payload = {
          dataId,
          userName,
        };
        resObj.accessToken = jwt.sign(payload, secretKey, {
          expiresIn: config.jwt.expiresIn.accessToken,
        });
        resObj.refreshToken = jwt.sign(payload, secretKey, {
          expiresIn: config.jwt.expiresIn.refreshToken,
        });
      } else {
        resObj.code = codeObj.fail;
        resObj.message = "用户不存在";
      }
    }
    res.json(resObj);
  });
};
